/**
 * @project sso-token-start V1.0
 * @Title:  TokenLoginStore.java  
 * @Package com.gitee.kinbug.sso.store 
 * Copyright(c) 2020 KinBug Co. Ltd. 
 * All right reserved. 
 */
package com.gitee.kinbug.sso.store;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;

import com.gitee.kinbug.sso.model.AuthUser;
import com.gitee.kinbug.sso.properties.SsoTokenProperties;

import lombok.extern.slf4j.Slf4j;

/**
 * Description:TODO(token存取)
 * @author: KinBug
 */
@Slf4j
public class SsoServiceStore {

	public static SsoTokenProperties ssoTokenProperties;

	public static RedisTemplate<Object, Object> redisTemplate;
	
	public static int redisExpireMinite = 1440; // 1440 minite, 24 hour

	public SsoServiceStore(SsoTokenProperties ssoTokenProperties) {
		SsoServiceStore.redisExpireMinite = ssoTokenProperties.getRedisExpireMinite();
		SsoServiceStore.ssoTokenProperties = ssoTokenProperties;
	}

	/**
	 * get
	 * @param storeKey 缓存key
	 * @return AuthUser session对象
	 */
	public static AuthUser get(String storeKey) {

		String redisKey = redisKey(storeKey);
		Object objectValue = redisTemplate.opsForValue().get(redisKey);
		if (objectValue != null) {
			AuthUser ssoUser = (AuthUser) objectValue;
			return ssoUser;
		}
		return null;
	}

	/**
	 * remove
	 *
	 * @param storeKey 缓存key
	 */
	public static void remove(String storeKey) {
		String redisKey = redisKey(storeKey);
		try {
			redisTemplate.delete(redisKey);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * put
	 *
	 * @param storeKey 缓存key
	 * @param ssoUser session对象
	 */
	public static void put(String storeKey, AuthUser ssoUser) {
		String redisKey = redisKey(storeKey);
		int time = redisExpireMinite * 60;
		try {
			if (time > 0) {
				redisTemplate.opsForValue().set(redisKey, ssoUser, time, TimeUnit.SECONDS);
			} else {
				redisTemplate.opsForValue().set(redisKey, ssoUser);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * put
	 *
	 * @param sessionId sessionId
	 * 
	 */
	private static String redisKey(String sessionId) {
		return ssoTokenProperties.getAuthKey().concat("#").concat(sessionId);
	}

}
